package com.bocai.freeman.view.activitys;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.bocai.freeman.R;
import com.bocai.freeman.base.BaseActivity;
import com.bocai.freeman.model.bean.UserBean;
import com.bocai.freeman.presenter.UserPresenter;
import com.bocai.freeman.utils.SP;
import com.bocai.freeman.utils.SpKey;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by admin on 2016/5/17.
 */
public class LoginActivity extends BaseActivity {

    @Bind(R.id.et_phone)
    EditText mEtPhone;
    @Bind(R.id.et_pwd)
    EditText mEtPwd;
    @Bind(R.id.btn_login)
    Button mBtnLogin;
    @Bind(R.id.tv_register)
    TextView mTvRegister;
    @Bind(R.id.tv_forget_pwd)
    TextView mTvForgetPwd;
    @Bind(R.id.toolbar)
    Toolbar mToolbar;

    private UserPresenter mUserPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        initEvent();
    }

    @Override
    protected void initEvent() {
        mToolbar.setNavigationIcon(R.mipmap.left_return);
        mToolbar.setNavigationOnClickListener(v -> onBackPressed());

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(Color.TRANSPARENT);
            getWindow()
                    .getDecorView()
                    .setSystemUiVisibility(
                            View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        }

        click(mBtnLogin).subscribe(o -> {
            loginRequest();
        });

        click(mTvRegister).subscribe(o -> startActivity(new Intent(LoginActivity.this, RegisterActivity.class)));

        click(mTvForgetPwd).subscribe(o -> startActivity(new Intent(LoginActivity.this, ForgetPwdActivity.class)));

    }

    private void loginRequest() {
        if (mUserPresenter == null)
            mUserPresenter = new UserPresenter(this, this);
        String tel = mEtPhone.getText().toString();
        String pwd = mEtPwd.getText().toString();
        mUserPresenter.login(tel, pwd);
    }

    @Override
    public void setData(Object obj) {
        if (obj instanceof UserBean) {
            UserBean bean = (UserBean) obj;
            showToast("登录成功");
            SP.put(this, SpKey.USERID,bean.getId());
            startActivity(new Intent(this, HomeActivity.class));
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }
}
